Date.now = Date.now || function() {
    return +new Date;
};
!function($) {

    $(function() {

        var isRgbaSupport = function() {
            var value = 'rgba(1,1,1,0.5)',
                    el = document.createElement('p'),
                    result = false;
            try {
                el.style.color = value;
                result = /^rgba/.test(el.style.color);
            } catch (e) {
            }
            el = null;
            return result;
        };
        var toRgba = function(str, alpha) {
            var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
            var matches = patt.exec(str);
            return "rgba(" + parseInt(matches[1], 16) + "," + parseInt(matches[2], 16) + "," + parseInt(matches[3], 16) + "," + alpha + ")";
        };
        // chart js
        var generateSparkline = function($re) {
            $(".sparkline").each(function() {
                var $data = $(this).data();
                if ($re && !$data.resize)
                    return;
                if ($data.type == 'bar') {
                    !$data.barColor && ($data.barColor = "#3fcf7f");
                    !$data.barSpacing && ($data.barSpacing = 2);
                    $(this).next('.axis').find('li').css('width', $data.barWidth + 'px').css('margin-right', $data.barSpacing + 'px');
                }
                ;
                ($data.type == 'pie') && $data.sliceColors && ($data.sliceColors = eval($data.sliceColors));
                // $data.fillColor && ($data.fillColor.indexOf("#") !== -1) && isRgbaSupport() && ($data.fillColor = toRgba($data.fillColor, 0.5));
                $data.spotColor = $data.minSpotColor = $data.maxSpotColor = $data.highlightSpotColor = $data.lineColor;
                $(this).sparkline($data.data || "html", $data);
                if ($(this).data("compositeData")) {
                    var $cdata = {};
                    $cdata.composite = true;
                    $cdata.spotRadius = $data.spotRadius;
                    $cdata.lineColor = $data.compositeLineColor || '#a3e2fe';
                    $cdata.fillColor = $data.compositeFillColor || '#e3f6ff';
                    $cdata.highlightLineColor = $data.highlightLineColor;
                    $cdata.spotColor = $cdata.minSpotColor = $cdata.maxSpotColor = $cdata.highlightSpotColor = $cdata.lineColor;
                    isRgbaSupport() && ($cdata.fillColor = toRgba($cdata.fillColor, 0.5));
                    $(this).sparkline($(this).data("compositeData"), $cdata);
                }
                ;
                if ($data.type == 'line') {
                    $(this).next('.axis').addClass('axis-full');
                }
                ;
            });
        };
        var sparkResize;
        $(window).resize(function(e) {
            clearTimeout(sparkResize);
            sparkResize = setTimeout(function() {
                generateSparkline(true)
            }, 500);
        });
        generateSparkline(false);
        // easypie
        var updatePie = function($that) {
            var $this = $that,
                    $text = $('span', $this),
                    $oldValue = $text.html(),
                    $newValue = Math.round(100 * Math.random());
            $this.data('easyPieChart').update($newValue);
            $({v: $oldValue}).animate({v: $newValue}, {
                duration: 1000,
                easing: 'swing',
                step: function() {
                    $text.text(Math.ceil(this.v));
                }
            });
        };
        $('.easypiechart').each(function() {
            var $barColor = $(this).data("barColor") || function($percent) {
                $percent /= 100;
                return "rgb(" + Math.round(255 * (1 - $percent)) + ", " + Math.round(255 * $percent) + ", 125)";
            },
                    $trackColor = $(this).data("trackColor") || "#c8d2db",
                    $scaleColor = $(this).data("scaleColor"),
                    $lineWidth = $(this).data("lineWidth") || 12,
                    $size = $(this).data("size") || 130,
                    $animate = $(this).data("animate") || 1000;
            $(this).easyPieChart({
                barColor: $barColor,
                trackColor: $trackColor,
                scaleColor: $scaleColor,
                lineCap: 'butt',
                lineWidth: $lineWidth,
                size: $size,
                animate: $animate,
                onStop: function() {
                    var $this = this.$el;
                    $this.data("loop") && setTimeout(function() {
                        $this.data("loop") && updatePie($this)
                    }, 2000);
                }
            });
        });
        $(document).on('click', '[data-toggle^="class:pie"]', function(e) {
            e && e.preventDefault();
            var $btn = $(e.target), $loop = $('[data-loop]').data('loop'), $target;
            !$btn.data('toggle') && ($btn = $btn.closest('[data-toggle^="class"]'));
            $target = $btn.data('target');
            !$target && ($target = $btn.closest('[data-loop]'));
            $target.data('loop', !$loop);
            !$loop && updatePie($('[data-loop]'));
        });
        // combodate
        $(".combodate").each(function() {
            $(this).combodate();
            $(this).next('.combodate').find('select').addClass('form-control');
        });
        // datepicker
        $(".datepicker").each(function() {
            $(this).datepicker();
        });

        // dropfile
        $('.dropfile').each(function() {
            var $dropbox = $(this);
            if (typeof window.FileReader === 'undefined') {
                $('small', this).html('File API & FileReader API not supported').addClass('text-danger');
                return;
            }

            this.ondragover = function() {
                $dropbox.addClass('hover');
                return false;
            };
            this.ondragend = function() {
                $dropbox.removeClass('hover');
                return false;
            };
            this.ondrop = function(e) {
                e.preventDefault();
                $dropbox.removeClass('hover').html('');
                var file = e.dataTransfer.files[0],
                        reader = new FileReader();
                reader.onload = function(event) {
                    $dropbox.append($('<img>').attr('src', event.target.result));
                };
                reader.readAsDataURL(file);
                return false;
            };
        });
        // fuelux pillbox
        var addPill = function($input) {
            var $text = $input.val(), $pills = $input.closest('.pillbox'), $repeat = false, $repeatPill;
            if ($text == "")
                return;
            $("li", $pills).text(function(i, v) {
                if (v == $text) {
                    $repeatPill = $(this);
                    $repeat = true;
                }
            });
            if ($repeat) {
                $repeatPill.fadeOut().fadeIn();
                return;
            }
            ;
            $item = $('<li class="label bg-default">' + $text + '<input name="' + $input.data('name') + '" type="hidden" value="' + $text + '"></li> ');
            $item.insertBefore($input);
            $input.val('');
            $pills.trigger('change', $item);
        };
        $('.pillbox input').on('blur', function() {
            addPill($(this));
        });
        $('.pillbox input').on('keypress', function(e) {
            if (e.which == 13) {
                e.preventDefault();
                addPill($(this));
            }
        });
        // slider
        $('.slider').each(function() {
            $(this).slider();
        });
        // wizard
        $(document).on('click', '[data-wizard]', function(e) {
            var $this = $(this), href;
            var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, ''));
            var option = $this.data('wizard');
            var item = $target.wizard('selectedItem');
            var $step = $(this).closest('.step-content').find('.step-pane:eq(' + (item.step - 1) + ')');
            if ($step.find('input, select, textarea').data('required') && !$step.find('input, select, textarea').parsley('validate')) {
                return false;
            } else {
                $target.wizard(option);
                var activeStep = (option == "next") ? (item.step + 1) : (item.step - 1);
                var prev = ($(this).hasClass('btn-prev') && $(this)) || $(this).prev();
                prev.attr('disabled', (activeStep == 1) ? true : false);
            }
        });
        // portlet
        $('.portlet').each(function() {
            $(".portlet").sortable({
                connectWith: '.portlet',
                iframeFix: false,
                items: '.portlet-item',
                opacity: 0.8,
                helper: 'original',
                revert: true,
                forceHelperSize: true,
                placeholder: 'sortable-box-placeholder round-all',
                forcePlaceholderSize: true,
                tolerance: 'pointer'
            });
        });
    });
    /*
     |********************************************************************************************
     | Data Tables
     |********************************************************************************************
     */



}(window.jQuery);
var oTable;
$(function() {

    if ($('.datatable').length) {


// DataTables Config (more info can be found at http://www.datatables.net/)	
//var oTable;
        if ($('.datatable').attr('data-source'))
        {
            oTable = $('.datatable').dataTable({
                "bJQueryUI": false,
                "bSortClasses": false,
                "aaSorting": [],
                "bAutoWidth": true,
                "bInfo": true,
                "sScrollY": "100%",
                "sScrollX": "100%",
                "bScrollCollapse": true,
                "sPaginationType": "full_numbers",
                "sDom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col col-sm-6'p>>",
                "bRetrieve": true,
                "fnServerData": function(sSource, aoData, fnCallback) {
                    if ($('.datatable').attr('data-source'))
                        $.ajax({
                            "dataType": 'json',
                            "type": "POST",
                            "url": sSource,
                            "data": aoData,
                            "success": fnCallback
                        });
                },
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": $('.datatable').attr('data-source'),
                "aoColumnDefs": [
                    {"bSortable": false, "aTargets": ["un-sortable"]},
                    {"sType": "html", "aTargets": ["html-sortable"]},
                    {"bVisible": false, "aTargets": ["col-hide"]}
                ],
                "oLanguage": {
                    "oPaginate": {
                        "sFirst": "<<",
                        "sLast": ">>",
                        "sNext": ">",
                        "sPrevious": "<"
                    }
                }
            });
        } else {

            oTable = $('.datatable').dataTable({
                "bJQueryUI": true,
                "bSortClasses": false,
                "aaSorting": [],
                "bAutoWidth": true,
                "bInfo": true,
                "sScrollY": "100%",
                "sScrollX": "100%",
                "bScrollCollapse": true,
                "sPaginationType": "full_numbers",
                "bRetrieve": true,
                "sAjaxSource": $('.datatable').attr('data-source'),
                "aoColumnDefs": [
                    {"bSortable": false, "aTargets": ["un-sortable"]}
                ]
            });
        }
    }

    $('#datatable_custom_search_btn').click(function() {
        var searchKey = $('#datatable_custom_search').val();
        $('.dataTables_filter input').val(searchKey);
        $('.dataTables_filter input').trigger('keyup');
    });
    
    $('#datatable_custom_search').change(function() {
        var searchKey = $('#datatable_custom_search').val();
        $('.dataTables_filter input').val(searchKey);
        $('.dataTables_filter input').trigger('keyup');
    });
    
    $('.pdf_delete_btn').click(function() {
        $clicked_btn = $(this);
        $.post($clicked_btn.attr('href'), function() {
            $clicked_btn.parent().parent().find('.pdf_thumb').remove();
            $clicked_btn.remove();
        });
        return false;
    });
});
$(document).on("click", ".tbl-delete-row", function() {
    var btn = $(this);
    bootbox.confirm("Are you sure?", function(result) {
        if (result) {
            $.post(btn.attr('rel'), function() {
                oTable.fnDraw(false);
            });
        }
    });

    return false;
});
$(document).on("click", ".tbl_active_btn", function() {
    var btn = $(this);
    $.post($(this).attr('rel'), function() {
        btn.toggleClass('status_1');
        btn.toggleClass('status_0');
    });
    return false;
});
$(function() {
    tinymce.init({
        selector: ".tinymce_selector",
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste moxiemanager"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
    });
});

$(function() {
    if ($("#lifeStyleTags").length != 0) {
        var lifestyle_tags = '';
        lifestyle_tags = $('#lifeStyleTags').val();
        lifestyle_tags = lifestyle_tags.split(',');
        var lifestyle_url = $('#lifeStyleTags').data('url');
        $('#lifeStyleTags').val('');
        $('#lifeStyleTags')
                .textext({
                    tags: {
                        items: lifestyle_tags
                    },
                    plugins: 'autocomplete tags ajax',
                    ajax: {
                        url: lifestyle_url,
                        dataType: 'json',
                        cacheResults: false
                    }
                });
    }

});

$(function() {
    if ($("#locationTags").length != 0) {
        var locationTags = '';
        locationTags = $('#locationTags').val();
        locationTags = locationTags.split(',');
        var location_url = $('#locationTags').data('url');
        $('#locationTags').val('');
        $('#locationTags')
                .textext({
                    tags: {
                        items: locationTags
                    },
                    plugins: 'autocomplete tags ajax',
                    ajax: {
                        url: location_url,
                        dataType: 'json',
                        cacheResults: false
                    }
                });
    }
});




$('#datePicker').daterangepicker({
    ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
        'Last 7 Days': [moment().subtract('days', 6), moment()],
        'Last 30 Days': [moment().subtract('days', 29), moment()],
        'This Month': [moment().startOf('month'), moment().endOf('month')],
        'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
    },
    startDate: moment().subtract('days', 29),
    endDate: moment()
});

$('.filter-toggle').click(function() {
    event.stopPropagation();
    $('.widget-filter').toggleClass('active');
});

$('.widget-filter').click(function(event) {
    event.stopPropagation();
});

$('body').click(function(e) {
    $('.widget-filter').removeClass('active');
});

$('.editPrice').click(function() {
    $(this).toggleClass('active');
});

$(document).on("click", ".bootbox-ajax-alert", function() {
    var btn = $(this);
    if (btn.attr('href')) {
        $.ajax({
            dataType: 'html',
            url: btn.attr('href')
        }).done(function(msg) {
            bootbox.dialog({
                message: msg,
                title: 'MEMO',
                buttons: {
                    success: {
                        label: "CLOSE",
                        className: "btn-success"
                    }
                }
            });
        });
    }
    //btn.data('title')

    return false;
});